/**
* Copyright (c) By zengqh.
*
* This program is just for fun or demo, in the hope that it  
* will be useful, you can redistribute it and/or modify freely.
*
* Time: 2013/03/05
* File: RenderTarget.cpp
**/

#include "OGLRenderTargetCube.h"
#include "OGL.h"
#include "OGLTexture2D.h"

namespace HY
{

OGLRenderTargetCube::~OGLRenderTargetCube()
{
	release();
}

void OGLRenderTargetCube::release()
{
	if (handle_)
	{
		glDeleteFramebuffers( 1, &handle_ );

		checkGLError();

		handle_ = 0;
	}
}

OGLRenderTargetCube::OGLRenderTargetCube()
	: depth_texture_(0)
	, handle_(0)
	, has_depth_(false)
	, size_(0)
{
	color_texture_list_.resize(MAX_RENDER_TARGET_COLOR_BUFFER);
	for (int i = 0; i < (int)color_texture_list_.size(); ++i)
	{
		color_texture_list_[i] = 0;
	}


}

bool OGLRenderTargetCube::createFrameBuffer()
{
	glGenFramebuffers(1, &handle_);
	checkGLError();

	return true;
}

void OGLRenderTargetCube::setColorTexture(uint8 idx, Texture2D* tex, uint8 face)
{
	HY_ASSERT(idx < MAX_RENDER_TARGET_COLOR_BUFFER);

	uint32 handle = 0;

	OGLTexture2D* tex2d = static_cast<OGLTexture2D*>(tex);

	if (tex2d) handle = tex2d->getHandle();

	color_texture_list_[idx] = tex;

	glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, handle, 0 );
	checkGLError();
}

void OGLRenderTargetCube::setDepthTexture(Texture2D* tex)
{
	OGLTexture2D* tex2d = static_cast<OGLTexture2D*>(tex);

	uint32 handle = 0;

	if (tex2d)
	{
		handle = tex2d->getHandle();
	}

	depth_texture_ = tex;

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, handle, 0);
	checkGLError();
}

void OGLRenderTargetCube::bind()
{
	glBindFramebuffer(GL_FRAMEBUFFER, handle_);
	checkGLError();
}

void OGLRenderTargetCube::unbind()
{
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	checkGLError();
}

}